<template>
  <div class="trends">
    <div class="product-list">
      <ProductCard
        v-for="product in products"
        :key="product.id"
        :product="product"
        @imageLoad="handleImageLoad" />
    </div>
  </div>
</template>

<script setup lang="ts">
  /**
   * 动态页面
   * 瀑布流商品
   */
  import axios from 'axios'
  import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
  import ProductCard from '@/components/ProductCard.vue'

  // 瀑布流布局相关变量
  const columnHeights = ref<number[]>([])
  const containerWidth = ref(0)
  const cardWidth = 220 // 卡片固定宽度，与ProductCard.vue中的宽度一致
  const gap = 15 // 卡片间距

  // 商品列表数据
  const products = ref<any>()


  // 计算瀑布流布局
  const calculateLayout = () => {
    const container = document.querySelector('.product-list') as HTMLElement
    if (!container) return

    // 获取容器实际可用宽度（考虑滚动条）
    const containerStyle = window.getComputedStyle(container)
    const paddingLeft = parseFloat(containerStyle.paddingLeft)
    const paddingRight = parseFloat(containerStyle.paddingRight)
    containerWidth.value = container.clientWidth - paddingLeft - paddingRight

    // 动态计算间距，确保充分利用空间
    const minColumns = Math.floor(containerWidth.value / cardWidth)
    const dynamicGap = (containerWidth.value - minColumns * cardWidth) / (minColumns + 1)

    const cards = container.querySelectorAll('.product-card') as NodeListOf<HTMLElement>
    const columnsCount = minColumns

    columnHeights.value = new Array(columnsCount).fill(0)

    cards.forEach((card, index) => {
      const minHeight = Math.min(...columnHeights.value)
      const columnIndex = columnHeights.value.indexOf(minHeight)

      card.style.position = 'absolute'
      card.style.left = `${columnIndex * (cardWidth + dynamicGap) + dynamicGap}px`
      card.style.top = `${minHeight}px`

      columnHeights.value[columnIndex] += card.offsetHeight + dynamicGap
    })

    container.style.height = `${Math.max(...columnHeights.value)}px`
  }

  // 防抖函数
  const debounce = (fn: Function, delay: number) => {
    let timer: number
    return () => {
      clearTimeout(timer)
      timer = setTimeout(fn, delay)
    }
  }

  const debouncedCalculate = debounce(calculateLayout, 200)

  const loadedImagesCount = ref(0)
  const totalImages = ref(0)

  const handleImageLoad = () => {
    loadedImagesCount.value++
    if (loadedImagesCount.value === totalImages.value) {
      nextTick(() => {
        calculateLayout()
      })
    }
  }

  onMounted(() => {
    getProducts()
    totalImages.value = document.querySelectorAll('.product-image').length
    // Always calculate layout on mount
    calculateLayout()
    // Fallback in case images take too long to load
    setTimeout(calculateLayout, 500)
    window.addEventListener('resize', debouncedCalculate)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', debouncedCalculate)
  })

  const getProducts = () => {
    axios.get('/xiaotao/products').then((res) => {
      products.value = res.data
    })
  }
</script>

<style scoped>
  .product-list {
    /* position: relative; */
    width: 100%;
    margin-top: 10px;
    display: flex;
  }
</style>
